package com.hxh.wechat.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.UserHandle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.billy.android.swipe.SmartSwipe
import com.billy.android.swipe.consumer.SpaceConsumer
import com.billy.android.swipe.consumer.StretchConsumer
import com.google.gson.JsonObject
import com.hxh.wechat.R
import com.hxh.wechat.adpter.ContactAdapter
import com.hxh.wechat.api.UserApi
import com.hxh.wechat.api.UserApi.Companion.signMessage
import com.hxh.wechat.database.UserDbHelper
import com.hxh.wechat.model.*
import com.hxh.wechat.util.ClientSocket
import com.hxh.wechat.util.DBUtil
import com.hxh.wechat.util.DBUtil.Companion.getUser
import com.hxh.wechat.util.DBUtil.Companion.parseExtand
import com.hxh.wechat.voide.CallVideoActivity
import com.hxh.wechat.voide.CallVideoActivity.goChatVideo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import me.weyye.hipermission.HiPermission
import me.weyye.hipermission.PermissionCallback
import me.weyye.hipermission.PermissionItem
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.w3c.dom.Text
import java.io.IOException
import java.util.*
import kotlin.collections.ArrayList


class ContentFragment(var idContent: Int, var router: Router) : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        lateinit var inflate: View
        when (idContent) {
            R.id.ImageButton1 -> {
                //怎么写？
                val activityChat = ActivityChat()
                val chatView = activityChat.onCreateView(inflater, container, savedInstanceState)
                return chatView
            }
            R.id.ImageButton2 -> {
                //怎么写？
                val contactActivity = ContactActivity()
                return contactActivity.onCreateView(inflater, container, savedInstanceState)
            }
            R.id.ImageButton3 -> inflate = inflater.inflate(R.layout.find_page, container, false)
            R.id.ImageButton4 -> {
                inflate = inflater.inflate(R.layout.user_page, container, false);
                var userInfo = getUser(inflate.context)
                inflate.findViewById<TextView>(R.id.textView8).text = userInfo!!.nickname
                inflate.findViewById<ImageView>(R.id.imageView4).load(userInfo.faceImage)

                var userDbHelper = UserDbHelper(inflate.context)
                var user = userDbHelper.getUserInfoByUsername("test")
                inflate.findViewById<TextView>(R.id.textView9).text = user.toString();
                inflate.findViewById<TextView>(R.id.forcedOffline).setOnClickListener {
                    var intent = Intent("com.hxh.wechat.FORCE_OFFLINE")
                    inflate.context!!.sendBroadcast(intent);
                }
                inflate.findViewById<TableRow>(R.id.logout).setOnClickListener {
                    //注銷
                    DBUtil.logout(context, router);
                }
            }
        }
        return inflate
    }
}

class Router : BaseActivity() {
    private var currentFragmentId = 0 // 定义成员变量下标
    private var listIcon = ArrayList<Int>()
    private var listIconActive = ArrayList<Int>()

    private fun AskPermission() {
        val permissionItems: MutableList<PermissionItem> = java.util.ArrayList()
        permissionItems.add(
            PermissionItem(
                Manifest.permission.CAMERA,
                "相机",
                me.weyye.hipermission.R.drawable.permission_ic_camera
            )
        )
        permissionItems.add(
            PermissionItem(
                Manifest.permission.RECORD_AUDIO,
                "录音",
                me.weyye.hipermission.R.drawable.permission_ic_micro_phone
            )
        )
        HiPermission.create(this).permissions(permissionItems)
            .checkMutiPermission(object : PermissionCallback {
                override fun onClose() {}
                override fun onFinish() {
                    println("权限分配完成");
                    thisInit();
                }

                override fun onDeny(permission: String, position: Int) {}
                override fun onGuarantee(permission: String, position: Int) {}
            })
    }

    // 在此处定义按钮并处理点击事件
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.router)
        thisRouter = this;
        AskPermission()
    }

    companion object {
        private lateinit var context: Context
        val handler = Handler()
        var thisRouter = Router()
        fun receiveMsg(text: String) {
            var extand = parseExtand(text)
            var parseMsg = DBUtil.parseMsg(text)!!
            //解析是不是视频
            if (extand.equals("\"video\"")) {
                goChatVideo(this.context, getUser(context)!!.id, parseMsg.content)
                return;
            } else if (extand.equals("\"video-stop\"")) {
                handler.post {
                    DBUtil.popMsg("该用户未在线", this.context);
                }
                return
            }

            var friend = getUserById(context, parseMsg.sendId!!)!!
            var message = ChatPageActivity.ChatMessage(
                friend.friendFaceImage,
                friend.friendNickname,
                Date(),
                parseMsg.content,
                false,
                parseMsg.type
            )
            var isRead = true;
            if (!ChatPageActivity.contact.friendUserId.equals("xxx") && ChatPageActivity.contact.friendUserId == parseMsg.sendId) {
                //已读
                ChatPageActivity.chatMessageList.add(message)
                ChatPageActivity.notifyDataSetChanged()
                val position = ChatPageActivity.chatMessageList.size - 1
                GlobalScope.launch(Dispatchers.Main) {
                    ChatPageActivity.recyclerView.scrollToPosition(position)
                }
            } else {
                //未读取消息
                isRead = false;
                //改变快照页的数据变化
                var iterator = ActivityChat.starList.iterator()
                while (iterator.hasNext()) {
                    val it = iterator.next()
                    if (it.userId == friend.friendUserId) {
                        //删除该快照
                        iterator.remove()
                    }
                }
                //查看历史数据
                var historyData: ArrayList<ChatHistory> =
                    getUserChatHistoryData(context, friend.friendUserId)!!
                var readSize = 0;
                for (chatHistory in historyData) {
                    if (!chatHistory.isRead) {
                        readSize++;
                    }
                }
                ActivityChat.starList.add(
                    Star(
                        friend.friendUserId,
                        friend.friendFaceImage,
                        friend.friendNickname,
                        parseMsg.content,
                        Date(),
                        readSize + 1,
                        parseMsg.type
                    )
                )
            }

            //保存快照
            saveUserChatSnapshot(
                ChatSnapshot(
                    DBUtil.getUser(context)!!.id,
                    friend.friendUserId,
                    friend.friendFaceImage,
                    friend.friendNickname,
                    Date(),
                    parseMsg.content,
                    isRead,
                    parseMsg.type,
                ), context
            );
            //保存聊天信息
            saveUserChatHistory(
                ChatHistory(
                    parseMsg.msgId,
                    DBUtil.getUser(context)!!.id,
                    friend.friendUserId,
                    parseMsg.content,
                    false,
                    parseMsg.type,
                    isRead,
                    Date()
                ), context
            )

            //进行消息的签收
            signMessage(parseMsg.msgId)?.enqueue(
                object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        println("签收信息${parseMsg.msgId}=====>失败.")
                        println(e.stackTrace.toString())
                    }

                    @Throws(IOException::class)
                    override fun onResponse(call: Call, response: Response) {
                        println("签收信息${parseMsg.msgId}=====>成功.")
                    }
                })


            //更新聊天页数据
            ActivityChat.initStar()
        }

    }

    private fun thisInit() {
        /**
         * 主界面加载webscoket
         */
        ClientSocket.initSocket(this)
        //缓存数据
        setContactList(this);

        //缓存好友信息
        context = this;

        listIcon.add(0);
        listIcon.add(R.drawable.chatsvg);
        listIcon.add(R.drawable.booksvg);
        listIcon.add(R.drawable.findsvg);
        listIcon.add(R.drawable.usersvg);
        listIconActive.add(0);
        listIconActive.add(R.drawable.chatsvg_active);
        listIconActive.add(R.drawable.booksvg_active);
        listIconActive.add(R.drawable.findsvg_active);
        listIconActive.add(R.drawable.usersvg_active);

        //初始化第一个页面
        var identifierMain = resources.getIdentifier("ImageButton1", "id", packageName)
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.replace(
            R.id.container,
            ContentFragment(idContent = identifierMain, router = thisRouter)
        )
        fragmentTransaction.commit()
        currentFragmentId = identifierMain;
        findViewById<ImageButton>(currentFragmentId).setBackgroundResource(
            listIconActive.get(1)
        )
        for (i in 1..4) {
            var identifier = resources.getIdentifier("ImageButton" + i, "id", packageName)
            findViewById<ImageButton>(identifier).setOnClickListener(object : View.OnClickListener {
                override fun onClick(v: View?) {
                    val fragmentManager = supportFragmentManager
                    val fragmentTransaction = fragmentManager.beginTransaction()
                    fragmentTransaction.replace(
                        R.id.container,
                        ContentFragment(idContent = identifier, router = thisRouter)
                    )
                    //提交 切换frame
                    fragmentTransaction.commit()
                    //设置当前按钮下标
                    currentFragmentId = identifier
                    //按钮切换 激活状态
                    for (i in 1..4) {
                        findViewById<ImageButton>(
                            resources.getIdentifier(
                                "ImageButton" + i,
                                "id",
                                packageName
                            )
                        ).setBackgroundResource(listIcon.get(i))
                    }
                    findViewById<ImageButton>(currentFragmentId).setBackgroundResource(
                        listIconActive.get(i)
                    )

                }
            })
        }

    }


}